﻿using System;
using System.Web;
using FFIV.Lib.BusinessRules;
using FFIV.Lib.DataComponent;
using FFIV.Lib.IView.Articles;
using FFIV.Lib.Model;
using FFIV.Lib.Utilities;

namespace FFIV.Lib.Controlers.Admin
{
	public class EditArticleController
	{
		private readonly IEditArticle m_View;

		public EditArticleController(IEditArticle view)
		{
			m_View = view;
		}

		public void LoadPage()
		{
			int id = ParamUtility.GetQueryStringValue("id", -1);
			if (id != -1)
			{
				AritcleDS.ArticlesDataTable table = ArticlesRules.GetArticleById(id);
				if (table.Rows.Count == 1)
				{
					AritcleDS.ArticlesRow row = table.Rows[0] as AritcleDS.ArticlesRow;
					if (row != null)
					{
						CheckUserPermission(row.AuthorId);

						m_View.Title = row.Title;
						m_View.AuthorName = row.AuthorName;
						m_View.Categories = CategoriesUtility.GetCategories();
						m_View.CategoryId = row.CategoryId;
						m_View.Summary = row.Summary;
						m_View.Content = row.Content;
						m_View.Tags = row.Tags;
					}
				}
			}
		}

		public void UpdateArticle()
		{
			int id = ParamUtility.GetQueryStringValue("id", -1);
			ArticlesRules.UpdateArticleById(id, m_View.AuthorName, m_View.CategoryId, m_View.Title, m_View.Summary, m_View.Content, m_View.Tags, false);
			HttpContext.Current.Response.Redirect(UrlUtility.GetArticleDetailUrl(id));
		}

		public void AddDraft()
		{
			int id = ParamUtility.GetQueryStringValue("id", -1);
			ArticlesRules.UpdateArticleById(id, m_View.AuthorName, m_View.CategoryId, m_View.Title, m_View.Summary, m_View.Content, m_View.Tags, true);
			HttpContext.Current.Response.Redirect(UrlUtility.GetArticleDetailUrl(id));
		}


		private static void CheckUserPermission(Guid userId)
		{
			Permissions currentRole = UsersUtility.GetCurrentUserRole();
			if (currentRole == Permissions.Admin)
			{
				return;
			}

			Guid? currentId = UsersUtility.GetCurrentUserId();
			if (currentId == null || currentId != userId)
			{
				throw new PermissionException();
			}
		}
	}
}
